﻿Imports System.Text
Imports Kairyu.Extension

Namespace Save
    ''' <summary>
    ''' 削除コマンド生成クラス
    ''' </summary>
    ''' <remarks></remarks>
    Friend Class DeleteCommandFactory

        Private Shared WHERE_PARAMETER_PREFIX As String = "WP"

        ''' <summary>
        ''' 削除コマンドを作成します。
        ''' </summary>
        ''' <param name="def"></param>
        ''' <param name="trn"></param>
        ''' <param name="prefix"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Create(ByVal def As SaveDefinition, ByVal trn As IDbTransaction, ByVal prefix As String) As IDbCommand
            Return (New Core).CreateCommand(def, trn, prefix)
        End Function

        Private Class Core

            Private Property Definition As SaveDefinition

            Private Property Command As IDbCommand

            Private Property Prefix As String

            Public Function CreateCommand(ByVal def As SaveDefinition, ByVal trn As IDbTransaction, ByVal prefix As String) As IDbCommand
                Me.Definition = def
                Me.Prefix = prefix

                Me.Command = trn.Connection.CreateCommand
                Me.Command.Transaction = trn

                Me.BuildCommand()

                Return Me.Command
            End Function

            Private Sub BuildCommand()
                Dim s As New StringBuilder
                Dim cnt As Integer = 0

                '検索パラメータの追加、生成
                Dim addParameter As Func(Of Object, String) =
                    Function(val As Object) As String
                        Dim prm As IDbDataParameter = Me.Command.CreateParameter
                        prm.ParameterName = DeleteCommandFactory.WHERE_PARAMETER_PREFIX & cnt
                        prm.Value = val
                        Me.Command.Parameters.Add(prm)
                        cnt += 1
                        Return Me.Prefix & prm.ParameterName
                    End Function

                'コマンド文字列の追加
                Dim addCommand As Action(Of String) =
                    Sub(text As String)
                        s.Appenddelimiter(" AND ")
                        s.Append(text)
                    End Sub

                '列属性に更新条件を作成させる
                For Each item In Me.Definition.TableArchive.ColumnArchives.Select(Function(x) x.Value)
                    Dim arch As ColumnArchive = item
                    Dim c As ColumnAttribute = (From el In Me.Definition.TableAttribute.Columns Where el.ColumnName = arch.ColumnName).First
                    c.BuildSaveWhereCommand(Me.Definition.Model, item.ArchiveValue, addCommand, addParameter)
                Next

                Me.Command.CommandText = String.Format("DELETE FROM {0} WHERE {1}", Me.Definition.TableAttribute.TableFullName, s.ToString)
            End Sub
        End Class

    End Class

End Namespace
